<?php

namespace app\controller;

use think\annotation\route\Group;
use think\annotation\route\Route;
use app\BaseController;
use app\model\Menu;
use app\middleware\CheckToken;


#[Group("api")]
class MenuController extends BaseController
{

    protected $middleware = [CheckToken::class];

    #[Route("GET", "queryMenuTree")]
    public function queryMenuTree() {
        $menuList =  Menu::select();
        $tree = $this->buildTree($menuList->toArray(), '0');
        return json($tree);
    }


    #[Route("POST", "queryMenu")]
    public function queryMenuList(){
        $params = request()->post();
        $query = Menu::query();
        if (!empty($params['username'])) {
             halt($params['username']);
             $query->where('name', $params['username']);
        }
        $query->select();
        return json($query);
    }

    // 一个用来构建树状结构的私有方法
    private function buildTree(array $elements, $parentId ) {
        $branch = [];

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->buildTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children; // 将子节点添加到当前节点
                }
                $branch[] = $element; // 将当前节点加入树状结构
            }
        }

        return $branch;
    }
}